/**
 *All rights Reserved, Designed By Water
 */
package com.ja.util;

import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;


/**   
 * @ClassName:PayCrypt3Des   
 * @Description:java 3des CBC模式加解密处理类
 * @author:Water 
 * @date: 2015-7-13 下午5:13:08  
 * @version V2.0  
 */
public class PayCrypt3Des {
	
	/** 
     * 3desCBC模式加密 
     * @param encryptString 待加密字符串
     * @param encryptKey
     * @param iv
     * @return Base64编码的密文 
     * @throws Exception 
     */  
	public static String encrypt3DES(String encryptString, String encryptKey, String iv) throws Exception {
		byte encryptedData[];
		IvParameterSpec zeroIv = new IvParameterSpec(iv.getBytes("UTF-8"));
		SecretKeySpec key = new SecretKeySpec(encryptKey.getBytes("UTF-8"), "DESede");
		Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
		cipher.init(1, key, zeroIv);
		encryptedData = cipher.doFinal(encryptString.getBytes("UTF-8"));
		String  is3DesString= new String(org.apache.commons.codec.binary.Base64.encodeBase64(encryptedData));
		return is3DesString;
	}
	
	/** 
     * 3desCBC模式解密 
     * @param encryptString  3desCBC模式加密 后Base64编码的密文 
     * @param encryptKey
     * @param iv
     * @return 字符串明文
     * @throws Exception 
     */  

	public static String decrypt3DES(String decryptString,String encryptKey, String iv)throws Exception {
        Key deskey = null;
        DESedeKeySpec spec = new DESedeKeySpec(encryptKey.getBytes("UTF-8"));
        SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
        deskey = keyfactory.generateSecret(spec);
        Cipher cipher = Cipher.getInstance("desede" + "/CBC/PKCS5Padding");
        IvParameterSpec ips = new IvParameterSpec(iv.getBytes("UTF-8"));
        cipher.init(Cipher.DECRYPT_MODE, deskey, ips);
        byte[] decryptedData = cipher.doFinal(org.apache.commons.codec.binary.Base64.decodeBase64(decryptString.getBytes("UTF-8")));
        String  is3DesString= new String(decryptedData);
		return is3DesString;
    }
	
}
